<template>
  <t-dialog
    :header="header"
    :visible.sync="visible"
    :onClose="closeDialog"
    :closeOnOverlayClick="false"
    @confirm="onSubmit"
    :confirmBtn="{
        content: loading?'提交中...':'确认',
        theme: 'primary',
        loading: loading,
      }"
    width="60%"
    top="5%"
  >
    <t-form ref="form" :colon="true" :data="formData" labelWidth="100px" :rules="rules">
      <t-row style="row-gap:24px">
        <t-col :span="6" v-if="!userId">
          <t-form-item label="登录名称" name="userName">
            <t-input clearable autocomplete="off" v-model="formData.userName" :maxlength="20"
                     placeholder="请输入登录名称"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6" v-if="!userId">
          <t-form-item label="用户密码" name="password">
            <t-input clearable autocomplete="new-password" type="password" v-model="formData.password" :maxlength="20"
                     placeholder="请输入密码"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="真实姓名" name="nickName">
            <t-input clearable v-model="formData.nickName" :maxlength="30" placeholder="请输入真实姓名"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="用户性别" name="sex">
            <t-select placeholder="请选择性别"  :options="dict.type.sys_user_sex" v-model="formData.sex">
            </t-select>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="归属单位" name="departmentId">
            <t-tree-select filterable clearable :treeProps="{keys: {value: 'id'}}" v-model="formData.departmentId" :data="deptOptions" placeholder="请选择归属单位">

            </t-tree-select>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="手机号码" name="phonenumber">
            <t-input clearable v-model="formData.phonenumber" :maxlength="11" placeholder="请输入手机号码"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="身份证号" name="idCard">
            <t-input clearable v-model="formData.idCard" :maxlength="50" placeholder="请输入身份证号"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="角色" name="roleIds">
            <t-select multiple placeholder="请选择角色"  v-model="formData.roleIds">
              <t-option
                v-for="item in roleOptions"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
                :disabled="item.status === 1"
              ></t-option>
            </t-select>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="出生年月" name="birthDate">
            <t-date-picker  v-model="formData.birthDate" placeholder="请输入身份证号" style="width:100%" disabled/>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="邮箱" name="email">
            <t-input clearable v-model="formData.email" :maxlength="50" placeholder="请输入邮箱"></t-input>
          </t-form-item>
        </t-col>

        <t-col :span="6">
          <t-form-item label="职务" name="duty">
            <t-input clearable v-model="formData.duty"  placeholder="请输入职务"></t-input>
          </t-form-item>
        </t-col>

        <t-col :span="6">
          <t-form-item label="技术职称" name="profTitId">
            <t-tree-select  @change="onProfTitIdChange" clearable filterable :treeProps="{keys: {value: 'id',label:'name'}, valueMode: 'onlyLeaf'}"
                           v-model="formData.profTitId" :data="profTitOptions" placeholder="技术职称"></t-tree-select>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="职称" name="profTit">
            <t-select disabled placeholder="请选择职称" filterable :options="dict.type.prof_tit" v-model="formData.profTit">
            </t-select>
          </t-form-item>
        </t-col>

        <t-col :span="6">
          <t-form-item label="学历" name="education">
            <t-select placeholder="请选择学历" :options="dict.type.education" filterable  v-model="formData.education">
            </t-select>
          </t-form-item>
        </t-col>


        <t-col :span="6">
          <t-form-item label="学位" name="degree">
            <t-select placeholder="请选择学位" :options="dict.type.degree" filterable  v-model="formData.degree">
            </t-select>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="学校" name="school">
            <t-input clearable v-model="formData.school"  placeholder="请输入学校"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="专业" name="majorName">
            <t-input
              v-model="formData.majorName"
              clearable
              placeholder="请输入专业"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="现从事专业" name="majorNowName">
            <t-input
              v-model="formData.majorNowName"
              clearable
              placeholder="请输入专业"
            />
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="岗位" name="postIds">
            <t-select multiple placeholder="请选择岗位"  v-model="formData.postIds">
              <t-option
                v-for="item in postOptions"
                :key="item.id"
                :label="item.postName"
                :value="item.id"
                :disabled="item.status === 1"
              ></t-option>
            </t-select>
          </t-form-item>
        </t-col>


        <t-col :span="12">
          <t-form-item label="状态" name="status">
            <t-radio-group :options="dict.type.sys_normal_disable" v-model="formData.status">
            </t-radio-group>
          </t-form-item>
        </t-col>
        <t-col :span="12">
          <t-form-item label="备注" name="remark">
            <t-textarea
              v-model="formData.remark"
              placeholder="请输入内容"
            />
          </t-form-item>
        </t-col>
      </t-row>
    </t-form>
  </t-dialog>
</template>

<script>
import {
  getUser,
  updateUser,
  addUser
} from "@/api/system/user";
import { treeselect, treeselectParty } from "@/api/system/dept";
import { encrypt } from "@/utils/jsencrypt";

export default {
  name: "add-edit-user",
  dicts: ["sys_normal_disable", "sys_user_sex","duty","prof_tit","degree","education"],
  props: ['header', 'userId'],
  data() {
    return {
      profTitOptions: [],
      visible: true,
      loading: false,
      sex: '',
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      deptOptionsParty: [],
      deptOptions: [],
      formData: {
        id: undefined,
        departmentId: null,
        profTitId: null,
        majorName:'',// 专业
        majorNowName: '',
        degree:'',
        school:'',
        profTit:'',
        duty:'',
        userName: '',
        nickName: '',
        password: '',
        phonenumber: '',
        email: '',
        sex: '',
        idCard: '',
        birthDate: '',
        education: '',
        status: "0",
        remark: '',
        postIds: [],
        roleIds: [],
      },
      // 表单校验
      rules: {
        userName: [
          {
            required: true,
            message: "登录名不能为空",
          },
          {
            min: 2,
            max: 20,
            message: "登录名称长度必须介于 2 和 20 之间",
          },
        ],
        departmentId: [
          {
            required: true,
            message: "归属单位不能为空",
          },
        ],
        nickName: [
          {
            required: true,
            message: "真实姓名不能为空",
          },
        ],
        idCard: [
          {
            required: true,
            message: "身份证号不能为空",
          },
          {
            message: "身份证号不正确",
            pattern: /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/,
          },
        ],
        birthDate: [
          {
            required: true,
            message: "出生年月不符合格式",
          },
        ],
        password: [
          {
            required: true,
            message: "用户密码不能为空",
          },
          {
            pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9~!@#$%^&*]{8,20}/,
            message: '请输入 8-20 个字符，需同时包含数字、大小写字母以及特殊符号',
            type: 'error',
            trigger: 'blur'
          },
        ],
        // email: [
        //   {
        //     required: true,
        //     message: "邮箱不能为空",
        //   },
        //   {email: {ignore_max_length: true}, message: '请输入正确的邮箱地址'}
        // ],
        sex: [
          {
            required: true,
            message: "性别不能为空",
          },
        ],
        phonenumber: [
          {
            required: true,
            message: "手机号不能为空",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
          },
        ],
        roleIds: [
          {required: true, validator: (val) => val.length > 0, message: "角色不能为空", type: "error"}
        ]
      }
    }
  },
  watch: {
    userId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getUser();
        }
      }
    },
    "formData.idCard": {
      immediate: true,
      handler(val) {
        const regu = /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/
        if (regu.test(val)) {
          const temp = this.formData.idCard.slice(6, 14)
          this.formData.birthDate = `${temp.substring(0, 4)}-${temp.substring(4, 6)}-${temp.substring(6, 8)}`;
        } else {
          this.formData.birthDate = ''
        }
      }
    }
  },
  created() {
    if(!this.userId){
      this.getTreeSelect();
      this.getProfTitTreeSelect();
      getUser(0).then((response) => {
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    }
  },
  methods: {
    getProfTitTreeSelect() {
      return this.$api.system.profTit.list().then(response => {
        this.profTitOptions = this.handleTree(response.data, "id");
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onProfTitIdChange(val, content) {
      this.formData.profTit = content.node.data.level;
    },
    getUser(){
      Promise.all([treeselect(),this.getProfTitTreeSelect()]).then(res => {
        this.deptOptions = res[0].data;
        // this.deptOptionsParty = res[1].data;
        getUser(this.userId).then((response) => {
          this.formData = response.data;
          this.postOptions = response.posts;
          this.roleOptions = response.roles;
          this.formData.postIds = response.postIds;
          this.formData.roleIds = response.roleIds;
        }).catch((e) => {
          this.$message.error(e.toString());
        });
      }).catch((e) => {
        this.$message.error(e.toString());
      });

    },
    /** 查询部门下拉树结构 */
    getTreeSelect() {
      treeselect().then((res) => {
        this.deptOptions = res.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    /** 查询党组织下拉树结构 */
    getTreeSelectParty() {
      treeselectParty().then((res) => {
        this.deptOptionsParty = res.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onSubmit() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.loading = true;
          if (this.userId !== 0) {
            updateUser(this.formData).then((response) => {
              this.$message.success("修改成功");
              this.$emit("reload");
              this.$emit("update:visible", false);
              this.loading = false;
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          } else {
            addUser({
              ...this.formData,
              password: encrypt(this.formData.password)}
            ).then((response) => {
              this.$message.success("新增成功");
              this.$emit("reload");
              this.$emit("update:visible", false);
              this.loading = false;
            }).catch((e) => {
              this.loading = false;
              this.$message.error(e.toString());
            });
          }
        }
      });
    },
    closeDialog() {
      this.$emit("update:visible", false);
    },
  }
}
</script>

<style scoped>

</style>
